import React, { useDeferredValue, useState } from 'react'

// 父组件
export const SearchBox: React.FC = () => {
    const [kw, setKw] = useState('')
    // 2. 基于 kw 的值，为其创建出一个延迟版的 kw 值，命名为 deferredKw
    const deferredKw = useDeferredValue(kw)
    const onInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        setKw(e.currentTarget.value)
    }

    return (
        <div style={{ height: 500, overflowY: 'scroll' }}>
            <input type="text" value={kw} onChange={onInputChange} />
            <hr />
            <div style={{ opacity: kw !== deferredKw ? 0.3 : 1, transition: 'opacity 0.5s ease' }}>
                <SearchResult query={deferredKw} />
            </div>
        </div>
    )
}

// 子组件，渲染列表项
const SearchResult: React.FC<{ query: string }> = React.memo((props) => {
    if (!props.query) return
    const items = Array(40000)
        .fill(props.query)
        .map((item, i) => <p key={i}>{item}</p>)

    return items
})
const UseDeferredValuePage: React.FC = () => {
    return (<>
        <SearchBox></SearchBox>
    </>)
}
export default UseDeferredValuePage